package git.soulbgm.common.proxy;

import git.soulbgm.common.future.SyncFuture;
import git.soulbgm.common.pojo.ConsumerService;
import git.soulbgm.common.socket.TcpClient;
import git.soulbgm.utils.SerializeUtil;
import git.soulbgm.utils.StringUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2019-04-02 16:23
 * @description
 */
public class RemoteProcedureCallHandler implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String msgId = UUID.randomUUID().toString();
        ConsumerService consumerService = new ConsumerService();
        consumerService.setMsgId(msgId);
        Class<?> declaringClass = method.getDeclaringClass();
        String simpleName = declaringClass.getSimpleName();
        simpleName = StringUtil.toLowerCase(simpleName, 0, 1);
        consumerService.setId(simpleName);
        consumerService.setIntfc(declaringClass.getName());
        consumerService.setMethodName(method.getName());
        consumerService.setClasses(method.getParameterTypes());
        consumerService.setValues(args);
        byte[] data = SerializeUtil.serializer(consumerService);
        SyncFuture syncFuture = new SyncFuture();
        TcpClient.sendMsg(msgId, syncFuture, data);
        return syncFuture.get();
    }
}
